package com.jerry.chinesechess.controller;

import com.jerry.chinesechess.model.Board;
import com.jerry.chinesechess.model.Piece;
import com.jerry.chinesechess.model.Position;
import com.jerry.chinesechess.view.ChessBoardView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class GameController {
    private final Board board;
    private final ChessBoardView view;
    private Position selectedPosition;
    
    public GameController(Board board, ChessBoardView view) {
        this.board = board;
        this.view = view;
    }
    
    public void handleClick(Position position) {
        if (selectedPosition == null) {
            // 选择棋子
            Piece piece = board.getPieceAt(position);
            if (piece != null && piece.getPlayer() == board.getCurrentPlayer()) {
                selectedPosition = position;
                piece.setSelected(true);
                view.updateView();
            }
        } else {
            // 移动棋子
            if (board.movePiece(selectedPosition, position)) {
                board.getPieceAt(selectedPosition).setSelected(false);
                selectedPosition = null;
                view.updateView();
                
                // 检查游戏是否结束
                if (board.isPositionSafe()){
                    return;
                }else {
                    log.info("被将军了");
                }
                if (board.isCheckmate()) {
                    showGameOverDialog();
                }
            }
        }
    }

    private void showGameOverDialog() {
        log.info("game over");
    }

}